package com.etlmaster.executor.boot;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.LogWriter;

/**
 * 插件包加载类
 * 
 * @author Wugf
 * @date 2016-03-08
 */
public class PluginJarLoader {
	public static void loadJar(String path) {
		File libPath = null;
		if (path != null && path.length() > 0) {
			libPath = new File(DataCollectionUtils.getProperties(
					"steps_path"));
			LogWriter.addLog("DEBUG","插件路径为{}", libPath.getAbsolutePath());
			// 获取所有的.jar文件
			File[] jarFiles = libPath.listFiles(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.endsWith(".jar");
				}
			});

			if (jarFiles != null) {
				// 从URLClassLoader类中获取类所在文件夹的方法
				// 对于jar文件，可以理解为一个存放class文件的文件夹
				Method method;
				try {
					method = URLClassLoader.class.getDeclaredMethod("addURL",
							URL.class);
					
					// 获取系统类加载器
					URLClassLoader classLoader = (URLClassLoader) ClassLoader
							.getSystemClassLoader();
					for (File file : jarFiles) {
						boolean accessible = method.isAccessible();
						if (accessible == false) {
							method.setAccessible(true); // 设置方法的访问权限
						}
						URL url = file.toURI().toURL();
						try {
							method.invoke(classLoader, url);
							LogWriter.addLog("DEBUG","读取jar文件[name={}]", file.getName());
						} catch (Exception e) {
							LogWriter.addLog("ERROR","读取jar文件[name={}]失败", file.getName());
							LogWriter.addLog("DEBUG","失败信息为：{}",e.getMessage());
						} finally {
							method.setAccessible(accessible);
						}
					}
				} catch (NoSuchMethodException e1) {
					LogWriter.addLog("DEBUG","失败信息为：{}",e1.getMessage());
				} catch (SecurityException e1) {
					LogWriter.addLog("DEBUG","失败信息为：{}",e1.getMessage());
				} catch (MalformedURLException e1) {
					LogWriter.addLog("DEBUG","失败信息为：{}",e1.getMessage());
				}
			}
		}else{
			LogWriter.addLog("ERROR","在配置文件里没找到step的插件位置，请修改配置文件");
		}
	}

	public static void main(String[] args) {
		loadJar(DataCollectionUtils.getProperties("steps_path"));
	}

}
